﻿using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WikiMarkupConverter
{
    /// <summary>
    /// Provides helper methods on file and/or directory
    /// </summary>
    internal static class FileHelper
    {
        /// <summary>
        /// Get all files of a directory and sub-directory if in recursive mode.
        /// If the path is set to a file, returns this file path.
        /// </summary>
        /// <param name="path">Path of the file or directory to list.</param>
        /// <param name="recursive">Set to true to include sub-directories.</param>
        /// <param name="extensions"></param>
        /// <returns></returns>
        internal static async Task<List<string>> GetFilesAsync(string path, bool recursive, List<string> extensions)
        {
            var files = new List<string>();

            // Specified path is a file
            if (File.Exists(path))
            {
                files.Add(path);
                return files;
            }
            // Invalid path (not a directory or a file)
            if (!Directory.Exists(path))
                return files;

            if (!extensions.Any())
                return files;

            await Task.Run(() => files.AddRange(Directory.GetFiles(path).Where(s => extensions.Any(s.EndsWith))));

            if (recursive)
            {
                foreach (var directory in Directory.GetDirectories(path))
                {
                    files.AddRange(await GetFilesAsync(directory, true, extensions));
                }
            }

            return files;
        }

        internal static string GetDirectory(string defaultPath)
        {
            var dialog = new FolderBrowserDialog
                {
                    Description = "Select a folder",
                    ShowNewFolderButton = true,
                    SelectedPath = defaultPath
                };
            dialog.ShowDialog();

            return dialog.SelectedPath;
        }
    }
}
